<!--
  -    Copyright (c) 2018-2025, hycloud All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: hycloud
  -->
<template>
    <div class="execution">
        <basic-container>
            <avue-crud ref="crud"
                       :page.sync="page"
                       :data="tableData"
                       :permission="permissionList"
                       :table-loading="tableLoading"
                       :option="tableOption"
                       @on-load="getList"
                       @search-change="searchChange"
                       @refresh-change="refreshChange"
                       @size-change="sizeChange"
                       @current-change="currentChange"
                       @row-update="handleUpdate"
                       @row-save="handleSave"
                       @row-del="rowDel">
                       <template slot="menuLeft">
                            <el-button
                            icon="el-icon-circle-plus"
                            size="small"
                            type="primary"
                            @click="addform()">新增委托</el-button>
                        </template>
                        <template slot="menu" slot-scope="scope">
                            <el-button type="text"
                            icon="el-icon-edit"
                            size="small"
                            @click="edit(scope.row)">修改委托</el-button>
                            <el-button type="text"
                            icon="el-icon-delete"
                            size="small"
                            @click="del(scope.row)">删除</el-button>
                        </template>
            </avue-crud>
        </basic-container>
        <el-dialog
            :visible.sync="modal"
            v-if="modal"
            title="委托"
            class="wt-dialog"
            width="1300px"
            top="5vh"
            :close-on-click-modal="false"
            append-to-body>
                <el-form  ref="form" :model="form"  label-width="120px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="委托人" prop="categoryId">
                               <el-input  placeholder="请选择人员" v-model="withMember_str"  @focus="choseMember" >
                                <el-button slot="append" @click="choseMember" >选择</el-button>
                            </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="开始结束时间">
                                 <el-date-picker
                                    v-model="dataRange"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    format="yyyy年MM月dd日 HH:mm:ss"
                                    type="datetimerange"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <avue-crud ref="crud1"
                    class="flow-crud-table"
                    :data="tableData1"
                    :permission="permissionList"
                    :table-loading="tableLoading1"
                    :option="tableOption1"
                    @on-load="getList1">
            </avue-crud>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取 消</el-button>
                <el-button type="primary" @click="alarmHandle('form')">确 定</el-button>
            </span>
        </el-dialog>
        <choose-member v-if="showChose" :labelkey="labelkey" :url1="url1" :url2="url2" :title="title1" :columns1="columns1" :columns="columns" :type="type" :flKey="flKey" :chosedKey="chosedKey" :choselist="choselist"></choose-member>
    </div>
</template>

<script>
    import {fetchList, getObj, addObj, putObj, delObj} from '@/api/activiti/delegate'
    import {fetchList as fetchList1} from '@/api/activiti/oaconfig'
    import {fetchListSimple} from '@/api/admin/user'
    import chooseMember from '@/components/chooseMember'
    import eventBus from '@/util/eventBus'
    import {tableOption, tableOption1} from '@/const/crud/activiti/delegate'
    import {mapGetters} from 'vuex'

    export default {
        components: { chooseMember },
        data() {
            return {
                dataRange: [],
                searchForm: {},
                tableData: [],
                tableData1: [],
                btnType: 'add',
                dataobj: {},
                option: {},
                showChose: false,
                flKey: 'categoryId',
                url1: '',
                url2: '',
                type:'',
                columns:[],
                form: {},
                columns1:[],
                choselist:[],
                chosedKey: [],
                title1: '',
                withMember_str: '',
                labelkey: '',
                option1: {},
                modal: false,
                userList: [],
                atts: [],
                id: '',
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                tableLoading: false,
                tableLoading1: false,
                tableOption: tableOption,
                tableOption1: tableOption1,
            }
        },
        computed: {
            ...mapGetters(['permissions', 'tagList']),
            permissionList() {
                return {
                    addBtn: false,
                    delBtn: false,
                    editBtn: false
                };
            }
        },
        created() {
            this.eventBusHandle()
            fetchListSimple({size: -1}).then(res => {
                this.userList = res.data.data.records
            })
        },
        methods: {
            addform() {
                this.modal = true
                this.btnType = 'add'
            },
            closeDialog() {
                this.modal = false
                this.choselist = []
                this.chosedKey = []
                this.id = ''
                this.withMember_str = ''
            },
            del(item) {
                delObj(item.id).then(res => {
                    this.$message.success('删除成功')
                    this.getList(this.page)
                })
            },
            edit(row) {
                this.id = row.id
                this.choselist = []
                this.chosedKey = []
                this.modal = true
                this.btnType = 'edit'
                this.choselist = this.userList.filter(item => {
                    return item.username == row.attorney
                })
                this.choselist.map(item => {
                    this.chosedKey.push(item.userId)
                })
                this.withMember_str = this.choselist.map(item => {
                    return item.realname
                }).join(',')
                this.dataRange = [row.startTime, row.endTime]
                this.atts = row.processCode.split(',')
            },
            alarmHandle() {
                let params = {}
                if (!this.withMember_str) {
                    this.$message.error('请选择委托人')
                    return
                } else {
                    params.attorney = this.choselist[0].username
                }
                if (!this.dataRange.length) {
                    this.$message.error('请选择开始结束时间')
                    return
                } else {
                    params.startTime = this.dataRange[0]
                    params.endTime = this.dataRange[1]
                }
                if(!this.$refs.crud1.tableSelect.length) {
                    this.$message.error('请勾选表单')
                    return
                } else {
                    params.processCode = this.$refs.crud1.tableSelect.map(item => {
                        return item.code
                    }).join(',')
                    params.processCodeName = this.$refs.crud1.tableSelect.map(item => {
                        return item.name
                    }).join('|')
                }
                if (this.btnType == 'add') {
                    addObj(params).then(res => {
                        this.$message.success('新增委托成功')
                        this.closeDialog()
                        this.getList(this.page)
                    })
                } else {
                    params.id = this.id
                    putObj(params).then(res => {
                        this.$message.success('修改委托成功')
                        this.closeDialog()
                        this.getList(this.page)
                    })
                }
                
            },
            eventBusHandle () {
                let _this = this
                eventBus.$on('getMember', function (data) {
                    _this.choselist = []
                    _this.chosedKey = []
                    _this.form.withMember = JSON.stringify(data.withMember)
                    _this.withMember_str = data.withMember_choose_member
                    _this.choselist = data.withMember
                    data.withMember.map(item => {
                        _this.chosedKey.push(item.userId)
                    })
                })
            },
            choseMember () {
                this.type = "radio"
                this.labelkey = 'withMember_choose_member'
                this.url1 = '/admin/dept/tree'
                this.url2 = '/admin/user/page/simple'
                this.title1 = '组织机构'
                this.flKey = 'deptId'
                this.columns = [
                {
                    title: '用户名',
                    dataIndex: 'username',
                    key: 'username',
                },
                {
                    title: '姓名',
                    key: 'realname',
                    dataIndex: 'realname',
                },
                {
                    title: '所属部门',
                    dataIndex: 'deptId',
                    key:'deptId',
                    scopedSlots: { customRender: 'deptId' },
                },
                {
                    title: '岗位',
                    dataIndex: 'post',
                    key: 'post',
                    scopedSlots: { customRender: 'post' }
                }
                ]
                this.columns1 = [
                {
                    title: '用户名',
                    dataIndex: 'username',
                    key: 'username' 
                },
                {
                    title: '操作',
                    key: 'action',
                    scopedSlots: { customRender: 'action' },
                },
                ]
                this.showChose = true
            },
            getList(page, params) {
                this.tableLoading = true
                if (this.searchForm.dateRange) {
                    this.searchForm.startDate = this.searchForm.dateRange[0];
                    this.searchForm.endDate = this.searchForm.dateRange[1];
                }
                fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize
                }, params, this.searchForm )).then(response => {
                    this.tableData = response.data.data.records
                    this.page.total = response.data.data.total
                    this.tableLoading = false
                }).catch(() => {
                    this.tableLoading=false
                })
            },
            getList1(page, params) {
                const _this = this
                this.tableLoading1 = true
                fetchList1(Object.assign({
                    current: 1,
                    size: 10000
                })).then(response => {
                    this.tableData1 = response.data.data.records
                    this.tableLoading1 = false
                    if (this.btnType == 'add') {
                         _this.$refs.crud1.toggleSelection(this.tableData1)
                    } else {
                        let newList = []
                        _this.tableData1.map(item => {
                            _this.atts.map(citem => {
                                if(item.code == citem) {
                                    newList.push(item)
                                }
                            })
                        })
                        this.$refs.crud1.toggleSelection(newList)
                    }
                }).catch(() => {
                    this.tableLoading1 = false
                })
            },
            rowDel: function (row, index) {
                this.$confirm('是否确认删除ID为' + row.bizId, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delObj(row.bizId)
                }).then(data => {
                    this.$message.success('删除成功')
                    this.getList(this.page)
                })
            },
            handleUpdate: function (row, index, done,loading) {
                putObj(row).then(data => {
                    this.$message.success('修改成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            handleSave: function (row, done,loading) {
                addObj(row).then(data => {
                    this.$message.success('添加成功')
                    done()
                    this.getList(this.page)
                }).catch(() => {
                    loading();
                });
            },
            sizeChange(pageSize){
                this.page.pageSize = pageSize
            },
            currentChange(current){
                this.page.currentPage = current
            },
            searchChange(form, done) {
                this.searchForm = form
                this.page.currentPage = 1
                this.getList(this.page, form)
                done()
            },
            refreshChange() {
                this.getList(this.page)
            }
        }
    }
</script>
<style lang="scss">
.flow-crud-table{
    .avue-crud__menu{
        display: none;
    }
}
.wt-dialog{
    .el-date-editor--datetimerange.el-input__inner{
        width: 500px;
    }
}

</style>